package com.base.mine;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.MultiAutoCompleteTextView;
import android.widget.PopupWindow;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.facade.callback.NavCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.base.commonlib.base.CBaseBarMvpActivity;
import com.base.commonlib.sp.SpUtil;
import com.base.mine.adapter.AccountAdapter;
import com.base.mine.bean.AccountPwdBean;
import com.base.mine.config.RouteConfig;
import com.base.mine.databinding.ActivityPwdloginBinding;
import com.base.mine.presenter.PwdLoginPresenter;
import com.base.mine.view.PwdLoginView;
import com.base.share.ShareLoginEntity;
import com.google.gson.Gson;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by weikailiang on 2020/2/25.
 */
@Route(path = "/mine/pwdlogin")
public class PwdLoginActivity extends CBaseBarMvpActivity<PwdLoginPresenter> implements PwdLoginView {
    UMAuthListener authListener = new UMAuthListener() {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            ShareLoginEntity loginEntity = new Gson().fromJson(new Gson().toJson(data), ShareLoginEntity.class);
            switch (platform) {
                case QQ:
                    showMes("QQ授权成功：ID=" + loginEntity.getUid() + "\n姓名：" + loginEntity.getName() + "\n性别：" + loginEntity.getGender());
                    break;
                case WEIXIN:
                    showMes("微信授权成功：ID=" + loginEntity.getUid() + "\n姓名：" + loginEntity.getName() + "\n性别：" + loginEntity.getGender());
                    break;
                case SINA:
                    showMes("新浪微博授权成功：ID=" + loginEntity.getUid() + "\n姓名：" + loginEntity.getName() + "\n性别：" + loginEntity.getGender());
                    break;
            }


        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            showMes("授权失败");
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            showMes("取消授权");
        }
    };
    private ActivityPwdloginBinding mBinding;
    private UMShareAPI mShareAPI;
    private List<AccountPwdBean> mAccountPwdBeans = new ArrayList<>();
    private AccountAdapter mAccountAdapter;
    private ListView listView;
    private PopupWindow popupWindow;
    private boolean isOpen = false;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_pwdlogin;
    }

    @Override
    protected void init() {
        super.init();
        mBinding = (ActivityPwdloginBinding) mRootBinding;
        mPresenter = new PwdLoginPresenter(this, this);
        setBackNavigation();
        setBarTitle("登录");
        mShareAPI = UMShareAPI.get(this);
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        mShareAPI.setShareConfig(config);

        mBinding.agreeMent.setChecked(true);
        mBinding.remmberPwd.setChecked(SpUtil.getRemmberPwd());
        Set<String> strings = new HashSet<>();
        strings = SpUtil.getStringSet(strings);
        mPresenter.start();
        try {
            JSONArray jsonArray = new JSONArray(strings.toString());
            for (int i = 0; i < jsonArray.length(); i++) {
                AccountPwdBean accountPwdBean = new AccountPwdBean();
                accountPwdBean.setAccount(jsonArray.getJSONObject(i).optString("account"));
                accountPwdBean.setPwd(jsonArray.getJSONObject(i).optString("pwd"));
                mAccountPwdBeans.add(accountPwdBean);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mBinding.register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance().build("/mine/login").navigation(mContext, new NavCallback() {
                    @Override
                    public void onArrival(Postcard postcard) {
                        finish();
                    }
                });

            }
        });
        mBinding.noPassLoginArrow.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (!isOpen) {
                    popupWindow = new PopupWindow(mContext);
                    popupWindow.setBackgroundDrawable(null);
                    popupWindow.setWidth(mBinding.loginInputPhone.getWidth());
                    popupWindow.setHeight(250);
                    popupWindow.setContentView(listView);
                    popupWindow.setOutsideTouchable(true);
                    popupWindow.showAsDropDown(mBinding.loginInputPhone, 0, 0);
                    if (!isOpen) {
                        isOpen = true;
                    }
                }
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        isOpen = false;
                    }
                });
            }
        });
        initListView();
        if (SpUtil.getRemmberPwd()) {
            mBinding.loginInputPhone.setText(SpUtil.getUserAccount());
            mBinding.loginInputPassword.setText(SpUtil.getUserPw());
        }
    }

    private void initListView() {
        listView = new ListView(this);
        listView.setBackgroundResource(R.drawable.bg_pop_list);
        listView.setDivider(null);
        listView.setVerticalScrollBarEnabled(false);
        listView.setAdapter(new AccountAdapter(mAccountPwdBeans, mContext));

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mBinding.loginInputPhone.setText(mAccountPwdBeans.get(position).getAccount());
                mBinding.loginInputPassword.setText(mAccountPwdBeans.get(position).getPwd());
                if (popupWindow != null) {
                    popupWindow.dismiss();
                    isOpen = false;
                }
            }
        });
    }

    @Override
    protected void start() {
        mBinding.phoneLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBinding.agreeMent.isChecked()) {
                    showMes("请同意注册协议");
                    return;
                }
                if (TextUtils.isEmpty(mBinding.loginInputPhone.getText().toString())) {
                    showMes("请输入手机号码");
                    return;
                }
                if (TextUtils.isEmpty(mBinding.loginInputPassword.getText().toString())) {
                    showMes("请输入密码");
                    return;
                }
                mPresenter.login(mBinding.loginInputPhone.getText().toString(), mBinding.loginInputPassword.getText().toString());
            }
        });
        mBinding.agreeMent.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!isChecked) {
                    mBinding.phoneLogin.setEnabled(false);
                } else {
                    mBinding.phoneLogin.setEnabled(true);
                }
            }
        });

        mBinding.forgetPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance().build("/forgetpw/pw").navigation();
            }
        });
        mBinding.loginQq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mShareAPI.isInstall(PwdLoginActivity.this, SHARE_MEDIA.QQ)) {
                    //第三方QQ登陆
                    mShareAPI.getPlatformInfo(PwdLoginActivity.this, SHARE_MEDIA.QQ, authListener);
                } else {
                    showMes("请先安装QQ");
                }
            }
        });

        mBinding.loginWechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mShareAPI.isInstall(PwdLoginActivity.this, SHARE_MEDIA.WEIXIN)) {
                    //第三方微信登陆
                    mShareAPI.getPlatformInfo(PwdLoginActivity.this, SHARE_MEDIA.WEIXIN, authListener);
                } else {
                    showMes("请先安装微信");
                }
            }
        });
        mBinding.loginWeibo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mShareAPI.isInstall(PwdLoginActivity.this, SHARE_MEDIA.SINA)) {
                    //第三方微博登录
                    mShareAPI.getPlatformInfo(PwdLoginActivity.this, SHARE_MEDIA.SINA, authListener);
                } else {
                    showMes("请先安装新浪微博");
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.release();
        mShareAPI.release();
    }

    @Override
    public boolean isRemmber() {
        return mBinding.remmberPwd.isChecked();
    }
}
